package com.atguigu.gmall.auth.config;

import com.atguigu.gmall.common.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@Configuration
@ConfigurationProperties(prefix = "auth.jwt")
@Data
@Slf4j
public class JwtProperties {

//    auth:
//    jwt:
//    privateKeyFilePath: F:\\keys\\rsa.pri
//    publicKeyFilePath: F:\\keys\\rsa.pub
//    secret: "asdas.asd321&"
//    expireTime: 10080
//    cookieTokenName: GMALL-TOKEN
//    unick: unick
    private String privateKeyFilePath;
    private String publicKeyFilePath;
    private String secret;
    private String cookieTokenName;
    private String unick;
    private Integer expireTime;
    private PublicKey publicKey;
    private PrivateKey privateKey;
    //判断公钥私钥文件是否存在 并根据文件生成公钥私钥对象的方法
    @PostConstruct
    public void init(){
        try {
            File privateFile = new File(privateKeyFilePath);
            File publicFile = new File(publicKeyFilePath);
            if(!privateFile.exists() || !publicFile.exists() ){
                //公钥私钥文件不存在
                RsaUtils.generateKey(publicKeyFilePath , privateKeyFilePath , secret);
            }
            //初始化公钥私钥对象
            publicKey = RsaUtils.getPublicKey(publicKeyFilePath);
            privateKey = RsaUtils.getPrivateKey(privateKeyFilePath);
        } catch (Exception e) {
            log.error("生成公钥私钥文件失败！！！！");
        }
    }

}
